<?php declare(strict_types=1);

namespace app\admin\controller;

use app\admin\Diluma;
use app\admin\service\HelpService;
use app\common\constant\RedisKeyConst;
use think\facade\Response;
use think\facade\Db;
use think\facade\View;
use think\facade\Log;
use think\cache\driver\Redis;

class Help extends Diluma
{
    /**
     * 单页
     * @return view
     */
    public function index()
    {
        return View::fetch();
    }

    /**
     * 列表数据
     * @return json
     */
    public function getHelpList(){
        $pageSize = $this->request->param('page_size', 10);

        $service = new HelpService();
        $list = $service->getHelpList($pageSize);

        return json(['code'=>0, 'count'=>$list->total(), 'data'=>$list->items()]);
    }

    /**
     * 编辑
     * @return string|\think\response\Json
     */
    public function edit()
    {
        $service = new HelpService();
        $post = $this->request->post();
        if(empty($post['title']) || empty($post['content'])){
            return json(['code'=>1, 'msg'=>'参数异常']);
        }
        $res = $service->updateOrInsert($post);
        if ($res) {
            return json(['code'=>0, 'msg'=>'编辑成功']);
        } else {
            return json(['code'=>1, 'msg'=>'编辑失败，稍后再试']);
        }
    }

    /**
     * 删除
     * @return \think\response\Json
     */
    public function delete(){
        $id = $this->request->param('id');
        if(!$id){
            return json(['code'=>1, 'msg'=>'参数异常']);
        }
        try {
            $service = new HelpService();
            $service->delete($id);
            return json(['code'=>0, 'msg'=>'删除成功']);
        } catch (ApiException $e) {
            Log::error('delete error:'. $e->getMessage());
            return json(['code'=>1, 'msg'=>$e->getMessage()]);
        }
    }
}